package model

import (
	"app/pkg/db"
	"app/pkg/log"
	"encoding/json"

	"github.com/garyburd/redigo/redis"
)

type Carousel struct {
	CommonStruct
	ImageUrl   string `gorm:"column:image_url" json:"imageUrl"`
	Name       string `gorm:"column:name" json:"name"`
	JumpUrl    string `gorm:"column:jump_url" json:"jumpUrl"`
	Type       int    `gorm:"column:type" json:"type"`
	CreateTime string `gorm:"column:create_time" json:"createTime"`
	UpdateTime string `gorm:"column:update_time" json:"updateTime"`
}

func NewCarouselModel() *Carousel { return &Carousel{} }

func (m *Carousel) TableName() string { return "carousel" }

func (m *Carousel) GetOne(where map[string]interface{}, columns []string) (item Carousel, err error) {
	conn, err := db.DB.MysqlDB.DefaultGormDB()
	if err != nil {
		return
	}
	err = conn.Model(&m).Select(columns).Where(where).Take(&item).Error
	return
}

func (m *Carousel) List(useCache bool) (list []Carousel) {
	if useCache {
		cacheBytes, err := redis.Bytes(db.DB.RedisPool.Get().Do("GET", "system:carousels"))
		if err == nil && len(cacheBytes) > 0 {
			err2 := json.Unmarshal(cacheBytes, &list)
			if err2 == nil {
				return
			}
		}
	}
	conn, err := db.DB.MysqlDB.DefaultGormDB()
	if err != nil {
		return
	}
	err = conn.Model(&m).Select("*").Order("id desc").Find(&list).Error
	if err != nil {
		return
	}
	if len(list) > 0 {
		bytes, err := json.Marshal(list)
		if err == nil {
			_, err3 := db.DB.RedisPool.Get().Do("SET", "system:carousels", string(bytes), "ex", 86400)
			if err3 != nil {
				log.NewError("system:carousels cache err", err3)
			}
		}
	}
	return list
}

func (m *Carousel) Add(carousel *Carousel) (err error) {
	conn, err := db.DB.MysqlDB.DefaultGormDB()
	if err != nil {
		return
	}
	err = conn.Model(&m).Omit("create_time", "update_time").Create(carousel).Error
	return
}

func (m *Carousel) Edit(where, columns map[string]interface{}) (err error) {
	conn, err := db.DB.MysqlDB.DefaultGormDB()
	if err != nil {
		return
	}
	err = conn.Model(&m).Omit("create_time", "update_time").Where(where).Updates(columns).Error
	return
}
func (m *Carousel) Delete(id int64) (err error) {
	conn, err := db.DB.MysqlDB.DefaultGormDB()
	if err != nil {
		return
	}
	err = conn.Delete(&m, id).Error
	return
}
